package com.danieltoms.io;

import java.io.IOException;

import javax.microedition.io.Connector;
import javax.microedition.io.HttpConnection;
import javax.microedition.io.HttpsConnection;

/*
 * Modified version of HttpConnectioHelper from:
 * 
 * http://java.sun.com/developer/J2METechTips/2000/tt1218.html
 * 
 * This handles redirects and secure connections
 */

public class HttpConnectionHelper
{
	private static final String HTTP = "http://";
	private static final String HTTPS = "https://";
	private static final String LOCATION = "Location";

	public interface Callback
	{
		void prepareRequest(String originalURL, HttpConnection conn) throws IOException;

		void preparePost(HttpConnection conn) throws IOException;
	}

	public static HttpConnection connect(String url) throws IOException
	{
		return handleConnection(url, HTTP, null);

	}

	public static HttpConnection connect(String url, Callback callback) throws IOException
	{
		HttpConnection conn = handleConnection(url, HTTP, callback);

		return conn;
	}

	public static HttpsConnection connectSecure(String url) throws IOException
	{
		return (HttpsConnection) handleConnection(url, HTTPS, null);
	}

	public static HttpsConnection connectSecure(String url, Callback callback) throws IOException
	{
		HttpsConnection conn = (HttpsConnection) handleConnection(url, HTTPS, callback);

		return conn;
	}

	private static HttpConnection handleConnection(String url, String protocol, Callback callback) throws IOException
	{
		HttpConnection conn = null;
		String originalURL = url;

		while (url != null)
		{

			conn = (HttpConnection) Connector.open(url);

			if (callback != null)
			{

				callback.prepareRequest(originalURL, conn);
				// todo, only do for post
				callback.preparePost(conn);

			}

			int rc = conn.getResponseCode();

			switch (rc)
			{
				case HttpConnection.HTTP_MOVED_PERM:
				case HttpConnection.HTTP_MOVED_TEMP:
				case HttpConnection.HTTP_SEE_OTHER:
				case HttpConnection.HTTP_TEMP_REDIRECT:
					url = conn.getHeaderField(LOCATION);
					if (url != null && url.startsWith("/*"))
					{
						StringBuffer b = new StringBuffer();
						b.append(protocol);
						b.append(conn.getHost());
						b.append(':');
						b.append(conn.getPort());
						b.append(url);
						url = b.toString();
					}
					conn.close();
					break;
				default:
					url = null;
					break;
			}
		}
		return conn;
	}
}
